package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {

    @Resource
    private WorkerCertificationMapper workerCertificationMapper;
    @Resource
    private WorkerCertificationAuditMapper workerCertificationAuditMapper;

    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    /**
     * 服务提交认证相关接口
     *
     * @param workerCertificationAuditAddReqDTO
     */
    @Override
    @Transactional
    public void certificationAudit(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        //获取属性拷贝
        WorkerCertification workerCertification = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertification.class);
        workerCertification.setCertificationMaterial(workerCertificationAuditAddReqDTO.getCertificationMaterial());
        CurrentUserInfo currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            // 使用getId()方法获取Long类型的用户ID
            workerCertification.setId(currentUser.getId());
        } else {
            throw new IllegalStateException("无法获取当前用户信息");
        }
        workerCertification.setIdCardNo(workerCertificationAuditAddReqDTO.getIdCardNo());
        workerCertification.setBackImg(workerCertificationAuditAddReqDTO.getBackImg());
        workerCertification.setFrontImg(workerCertificationAuditAddReqDTO.getFrontImg());
        workerCertification.setName(workerCertificationAuditAddReqDTO.getName());
        //1.认证中   2.认证成功   3.失败
        //提交到表中状态变为认证中
        workerCertification.setCertificationStatus(1);
        //提交到服务认证表
        workerCertificationMapper.insert(workerCertification);
        WorkerCertificationAudit workerCertificationAudit = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertificationAudit.class);
        workerCertificationAudit.setCertificationMaterial(workerCertificationAuditAddReqDTO.getCertificationMaterial());
        // 使用getId()方法获取Long类型的用户ID
        workerCertificationAudit.setServeProviderId(currentUser.getId());
        workerCertificationAudit.setIdCardNo(workerCertificationAuditAddReqDTO.getIdCardNo());
        workerCertificationAudit.setBackImg(workerCertificationAuditAddReqDTO.getBackImg());
        workerCertificationAudit.setFrontImg(workerCertificationAuditAddReqDTO.getFrontImg());
        workerCertificationAudit.setName(workerCertificationAuditAddReqDTO.getName());
        //提交到服务审核表
        workerCertificationAudit.setCertificationStatus(1);
        workerCertificationAudit.setAuditStatus(0);
        workerCertificationAuditMapper.insert(workerCertificationAudit);
    }

    /**
     * 查询最新的驳回原因接口
     *
     * @return
     */
    @Override
    public RejectReasonResDTO rejectReason() {
        //匹配审核表中机构ID等于当前用户id的数据中最新的驳回原因
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditMapper.selectOne(
                Wrappers.<WorkerCertificationAudit>lambdaQuery()
                        .eq(WorkerCertificationAudit::getServeProviderId, UserContext.currentUserId())
                        .orderByDesc(WorkerCertificationAudit::getAuditTime)
                        .last("limit 1")
                        .select(WorkerCertificationAudit::getRejectReason)
        );
        RejectReasonResDTO rejectReasonResDTO = new RejectReasonResDTO();
        if (workerCertificationAudit != null) {
            rejectReasonResDTO.setRejectReason(workerCertificationAudit.getRejectReason());
        }
        return rejectReasonResDTO;
    }

    /**
     * 分页查询
     *
     * @param workerCertificationAuditPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<WorkerCertificationAuditResDTO> pageQuery(WorkerCertificationAuditPageQueryReqDTO workerCertificationAuditPageQueryReqDTO) {
        //1.分页查询用户
        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(workerCertificationAuditPageQueryReqDTO, WorkerCertificationAudit.class);
        LambdaQueryWrapper<WorkerCertificationAudit> queryWrapper = Wrappers.<WorkerCertificationAudit>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getName()), WorkerCertificationAudit::getName, workerCertificationAuditPageQueryReqDTO.getName())
                .eq(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getIdCardNo()), WorkerCertificationAudit::getIdCardNo, workerCertificationAuditPageQueryReqDTO.getIdCardNo())
                .eq(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getCertificationStatus()), WorkerCertificationAudit::getCertificationStatus, workerCertificationAuditPageQueryReqDTO.getCertificationStatus())
                .eq(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getAuditStatus()), WorkerCertificationAudit::getAuditStatus, workerCertificationAuditPageQueryReqDTO.getAuditStatus());
        Page<WorkerCertificationAudit> workerCertificationAuditPage = workerCertificationAuditMapper.selectPage(page, queryWrapper);
        //2.封装数据
        return PageUtils.toPage(workerCertificationAuditPage, WorkerCertificationAuditResDTO.class);
    }

    /**
     * 审核
     *
     * @param certificationAuditReqDTO
     * @param id
     */
    @Override
    @Transactional
    public void auditById(CertificationAuditReqDTO certificationAuditReqDTO, Long id) {
        //根据申请id获取申请信息
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditMapper.selectById(id);
        if (certificationAuditReqDTO.getCertificationStatus() == 2) {
            //成功的话修改数据库
            workerCertificationAudit.setAuditStatus(1);
            workerCertificationAudit.setAuditTime(LocalDateTime.now());
            workerCertificationAudit.setUpdateTime(LocalDateTime.now());
            workerCertificationAudit.setCertificationStatus(2);
            CurrentUserInfo currentUser = UserContext.getCurrentUser();
            if (currentUser != null) {
                // 使用getId()方法获取Long类型的用户ID
                workerCertificationAudit.setAuditorId(currentUser.getId());
                workerCertificationAudit.setAuditorName(currentUser.getName());
            } else {
                throw new IllegalStateException("无法获取当前用户信息");
            }
            workerCertificationAuditMapper.updateById(workerCertificationAudit);
            WorkerCertification workerCertification = workerCertificationMapper.selectById(workerCertificationAudit.getServeProviderId());
            workerCertification.setCertificationStatus(2);
            workerCertification.setCertificationTime(LocalDateTime.now());
            workerCertification.setUpdateTime(LocalDateTime.now());
            workerCertificationMapper.updateById(workerCertification);
        } else {
            //失败的话更新状态，重新认证
            workerCertificationAudit.setAuditStatus(1);
            workerCertificationAudit.setAuditTime(LocalDateTime.now());
            workerCertificationAudit.setUpdateTime(LocalDateTime.now());
            workerCertificationAudit.setCertificationStatus(3);
            workerCertificationAudit.setRejectReason(certificationAuditReqDTO.getRejectReason());
            CurrentUserInfo currentUser = UserContext.getCurrentUser();
            if (currentUser != null) {
                // 使用getId()方法获取Long类型的用户ID
                workerCertificationAudit.setAuditorId(currentUser.getId());
                workerCertificationAudit.setAuditorName(currentUser.getName());
            } else {
                throw new IllegalStateException("无法获取当前用户信息");
            }
            workerCertificationAuditMapper.updateById(workerCertificationAudit);
            WorkerCertification workerCertification = workerCertificationMapper.selectById(workerCertificationAudit.getServeProviderId());
            workerCertification.setCertificationStatus(3);
            workerCertification.setCertificationTime(LocalDateTime.now());
            workerCertification.setUpdateTime(LocalDateTime.now());
            workerCertificationMapper.updateById(workerCertification);

            //目前还没有实现
            if (certificationAuditReqDTO.getCertificationStatus() == 2) {
                //重新认证
                WorkerCertificationAudit newAudit = new WorkerCertificationAudit();
                BeanUtil.copyProperties(workerCertificationAudit, newAudit);

                // 设置新的申请状态
                // 0-待审核
                newAudit.setAuditStatus(0);
                newAudit.setCertificationStatus(1);
                // 1-认证中
                newAudit.setCreateTime(LocalDateTime.now());
                newAudit.setUpdateTime(LocalDateTime.now());

                // 清空审核相关字段（因为是新的申请）
                newAudit.setAuditorId(null);
                newAudit.setAuditorName(null);
                newAudit.setAuditTime(null);
                newAudit.setRejectReason(null);

                // 插入新的认证申请记录
                workerCertificationAuditMapper.insert(newAudit);

                // 同时更新worker_certification表的状态为重新认证中
                // 1-认证中
                workerCertification.setCertificationStatus(1);
                workerCertification.setUpdateTime(LocalDateTime.now());
                workerCertificationMapper.updateById(workerCertification);
            }
        }
    }
}
